const net = require('net')

export default function getAvailablePort() {
  return new Promise((resolve, reject) => {
    const server = net.createServer()
    server.unref() // 当服务器不再监听新连接时，允许程序退出

    server.on('error', reject)

    server.listen(0, () => {
      const port = server.address().port
      server.close(() => {
        resolve(port)
      })
    })
  })
}
